<?php
/*
 * 喝水状态信息编辑及展示接口
 * */
class Apiv1_DrikingController extends Ctrl_Apiatk{
    //编辑    
    public function editAction(){
        $p = $_REQUEST;
        $pId = empty($p['sid'])?Tool_Fnc::ajaxMsg('老人ID不能为空'):Tool_Fnc::safe_string($p['sid']);
        $pTotal = empty($p['total'])?Tool_Fnc::ajaxMsg('喝水量不能为空'):Tool_Fnc::safe_string($p['total']);
        $pAt = empty($p['at'])?Tool_Fnc::ajaxMsg('时间点不能为空'):Tool_Fnc::safe_string($p['at']);

        $tSMO = new SeniorModel;
        $tId = $tSMO->field('id')->where('id = '.$pId)->fRow()['id'];
        if(empty($tId)){Tool_Fnc::ajaxMsg('该老人不存在');}

        $tDMO = new DrikingModel;
        $tTime = time();
        $tDData = $tDMO->field('id,total,times')->where('sid = '.$pId.' and date = "'.date('Y-m-d',$tTime).'" and at = '.$pAt)->fRow(); 
        if(empty($tDData)){//记录为空，添加操作
            $tData = array(
                'total' => $pTotal,
                'created' => $tTime,
                'times' => 1,
                'sid' => $pId,
                'date' => date('Y-m-d',$tTime),
                'week' => $this->getTimeWeek($tTime),
                'at' => $pAt,
            );
            if(!$tDMO->insert($tData)){
                Tool_Fnc::ajaxMsg('编辑失败 001');
            }
        } 
        Tool_Fnc::ajaxMsg('编辑成功',1);
    }
    //展示
    public function listAction(){
        $p = $_REQUEST;
        $pId = empty($p['sid'])?Tool_Fnc::ajaxMsg('老人ID不能为空'):Tool_Fnc::safe_string($p['sid']);
        $pDate = empty($p['date'])?'':Tool_Fnc::safe_string($p['date']);
        $pAt = empty($p['at'])?Tool_Fnc::ajaxMsg('时间点不能为空'):Tool_Fnc::safe_string($p['at']);
        $tSMO = new SeniorModel;
        $tId = $tSMO->field('id')->where('id = '.$pId)->fRow()['id'];
        if(empty($tId)){Tool_Fnc::ajaxMsg('该老人不存在');}

        $tDMO = new DrikingModel;
        //默认查询当天数据
        $time = time();
        $tWhere = ' sid = '.$pId.' and date = "'.date('Y-m-d',$time).'" and at = '.$pAt;
        if(!empty($pDate)){
           $tWhere = ' sid = '.$pId.' and date = "'.$pDate.'" and at = '.$pAt; 
        }
        $tDatas = $tDMO->field('id,sum(total) total,sum(times) times')->where($tWhere)->order('id desc')->fList();
        Tool_Fnc::ajaxMsg('',1,$tDatas);
    }
    //获取周几
    private function getTimeWeek($time, $i = 0) {
        $weekarray = array('1', '2', '3', "4", "5", "6", "7");
        $oneD = 24 * 60 * 60;
        return $weekarray[date("w", $time + $oneD * ($i-1))];
    }
}
?>
